package com.hangsu.train.components.web.controller;

import com.hangsu.train.components.entity.Device;
import com.hangsu.train.components.entity.Wanded;
import com.hangsu.train.components.params.*;
import com.hangsu.train.components.service.DeviceService;
import com.hangsu.train.components.service.WandedService;
import com.hangsu.train.core.result.Resp;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/device")
public class DeviceController {

    @Resource
    private DeviceService deviceService;

    @Resource
    private WandedService wandedService;

    @PostMapping("/list")
    public Resp<?> list(@RequestBody @Valid PageRequestParam param) throws Exception {
        Page<Device> page = deviceService.list(param);
        return Resp.ok(page);
    }

    @PostMapping("/create")
    public Resp<?> add(@RequestBody @Valid DeviceParam param) throws Exception {
        deviceService.add(param);
        return Resp.ok();
    }

    @PostMapping("/bind")
    public Resp<?> bind(@RequestBody @Valid DeviceBindParam param) throws Exception {
        Wanded wanded = wandedService.detail(new IdParam(param.getUserId()));
        Device devive= deviceService.getById(new IdParam(param.getId()));
        if(wanded!=null && devive!=null) {
            devive.setUserId(wanded.getId());
            devive.setUserName(wanded.getName());
            deviceService.update(devive);
        }
        return Resp.ok();
    }

    @PostMapping("/unbind")
    public Resp<?> unbind(@RequestBody @Valid IdParam param) throws Exception {
        Device device = deviceService.getById(param);
        device.setUserId(null);
        device.setUserName(null);
        deviceService.update(device);
        return Resp.ok();
    }

    @PostMapping("/delete")
    public Resp<?> del(@RequestBody @Valid IdParam param) throws Exception {
        deviceService.delete(param);
        return Resp.ok();
    }

}